import com.alibaba.moco.RedisPoolInstance
import com.alibaba.moco.util.BaseTypeUtil
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.apache.commons.lang.StringUtils
import redis.clients.jedis.Jedis
import script.GlobalValues
import script.moco.dto.OrderDetailDTO
import script.moco.dto.OrderInfo
import script.moco.dto.OrderPrice
import script.moco.dto.OrderPriceDetail
import script.v1.didiCallback.NoticeCallback
import script.v1.didiCallback.NotifyRequest

import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
 * 模拟 滴滴 創建訂單接口
 * Created by wb-lj240895 on 2016/11/1.
 */
def excute(request) {
    def params = request.getParameterMap();
    CreateOrderRequest req = BaseTypeUtil.mapToBean(params, CreateOrderRequest.class) as CreateOrderRequest
    def slurper = new JsonSlurper()
    Jedis redis = RedisPoolInstance.getRedisClient()
    //欢行异常判断
    def e = redis.hget(GlobalValues.KEY_EXCEPTION, "createOrder")
    if (!StringUtils.isBlank(e)) {
        System.out.println(e)
        def eJson = slurper.parseText(e)
        return eJson
    }
    String token = req.getAccess_token()
    System.out.println(token)

    if (token != null/* && redis.exists(token)*/) {
        //redis.del(token)
        //判断订单是否存在
        def orderId = req.getOrder_id()
        //redis.hexists()
        if (orderId != null && redis.exists(GlobalValues.KEY_ORDER + orderId)/* redis.exists(orderId)*/) {
            //保存訂單信息
            def reqMap = JsonOutput.toJson(req)
            OrderInfo orderInfo = BaseTypeUtil.mapToBean(params, OrderInfo.class) as OrderInfo
            OrderDetailDTO orderDetailDTO = new OrderDetailDTO()
            orderInfo.setId(req.getOrder_id())
            orderInfo.setStatus(300)
            orderDetailDTO.setOrder(orderInfo)


            CreateOrderResponse response = new CreateOrderResponse();
            response.setErrno(0)
            response.setErrmsg("SUCCESS")
            Data data = new Data()
            data.setCombo(new Combo())
            data.setOrder(new OrderDetail())
            data.setPrice(new Price())
            //处理预估价格
            String md5 = req.getDynamic_md5()
            System.out.println(md5)
            String couponStr = redis.get(GlobalValues.KEY_COUPON + md5)
            def coupon = slurper.parseText(couponStr)
            def coup = JsonOutput.toJson(coupon)
            if (coup.contains("price")) {
                def price = String.valueOf(coupon.price) //.getAt("price")

                System.out.println(price)
                data.getPrice().setEstimate(price)
                //费用详情不在这设置
                orderDetailDTO.setPrice(new OrderPrice())
                orderDetailDTO.getPrice().setTotal_price(price)
                List<OrderPriceDetail> detailPrice = new ArrayList<OrderPriceDetail>()
                /*  OrderPriceDetail det = new OrderPriceDetail();
                  System.out.println("设置费用详情")
                  det.setAmount("20.11")
                  det.setName("远途费\"或\"超出套餐部分远途费")
                  det.setType("empty_fee")
                  detailPrice.add(det)*/
                orderDetailDTO.getPrice().setDetail(detailPrice)
            }
            System.out.println("requst:" + JsonOutput.toJson(orderDetailDTO).toString())
            //redis.set(orderId,JsonOutput.toJson(orderDetailDTO).toString())
            redis.set(GlobalValues.KEY_ORDER + orderId, JsonOutput.toJson(orderDetailDTO).toString())
            redis.expire(GlobalValues.KEY_ORDER + orderId, GlobalValues.RIDES_EXPIRE)
            //订单超时回调
            Runnable runnable = new Runnable() {
                public void run() {
                    System.out.println("创建订单数据回调...");

                    //从redis中获取状态
                    def detailStr = redis.get(GlobalValues.KEY_ORDER + req.getOrder_id())
                    def detailJson = slurper.parseText(detailStr)
                    def status = detailJson.order.status
                    System.out.println("订单状态:" + status)
                    if (status == 300/* || status == "300"*/) {

                        //重写状态
                        orderDetailDTO.getOrder().setStatus(311)
                        redis.set(GlobalValues.KEY_ORDER + orderId, JsonOutput.toJson(orderDetailDTO).toString())

                        //通知回调
                        NoticeCallback noticeCallbackTool = new NoticeCallback();
                        NotifyRequest notifyRequest = new NotifyRequest();
                        notifyRequest.setOrderId(req.getOrder_id());
                        notifyRequest.setNotifyType(2);
                        notifyRequest.setNotifyDesc("订单超时");
                        String url = noticeCallbackTool.getCallbackUrlFromRequest(request, false)
                        if (StringUtils.isNotBlank(url)) {
                            noticeCallbackTool.handNotify(url, notifyRequest);
                        }
                    }

                }
            };
            ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();

            service.schedule(runnable, 60, TimeUnit.SECONDS);
            //new Thread(runnable).start();
            //处理callback_info
            if (req.getCallback_info() != null) {
                def info = req.getCallback_info()
                redis.set(GlobalValues.KEY_CALLBACK_INFO + orderId, info)
                if (info != null) {
                    String[] infoStrs = info.split(",")
                    //System.out.println(infoStrs)
                    if (infoStrs.length == 4) {
                        redis.set(GlobalValues.KEY_RELATION + infoStrs[0], orderId)
                    }
                }
            }

            //data.getPrice().setEstimate(String.valueOf(Math.abs(Math.random() * 500)))
            data.getCombo().setDistance(String.valueOf(Math.abs(Math.random() * 50)))
            data.getCombo().setFee(String.valueOf(Math.abs(Math.random() * 500)))
            data.getCombo().setTime(Math.abs(Math.random() * 150).intValue())
            data.getOrder().setCall_phone("17006428033")
            data.getOrder().setCity(String.valueOf(req.getCity()))
            data.getOrder().setClat(req.getClat())
            data.getOrder().setClng(req.getClng())
            data.getOrder().setDeparture_time(BaseTypeUtil.currentDateString())
            data.getOrder().setEnd_address(req.getEnd_address())
            data.getOrder().setEnd_name(req.getEnd_name())
            data.getOrder().setExtra_info(req.getExtra_info())
            data.getOrder().setFlat(req.getFlat())
            data.getOrder().setFlng(req.getFlng())
            data.getOrder().setId(req.getOrder_id())
            data.getOrder().setTlat(req.getTlat())
            data.getOrder().setTlng(req.getTlng())
            data.getOrder().setType(req.getType())
            data.getOrder().setPassenger_phone(req.getPassenger_phone())
            data.getOrder().setStatus(300)
            data.getOrder().setStart_address(req.getStart_address())
            data.getOrder().setStart_name(req.getStart_name())
            data.getOrder().setOrder_time(BaseTypeUtil.currentDateString())
            data.getOrder().setRequire_level(req.getRequire_level())


            response.setData(data)

            return JsonOutput.toJson(response)
        } else {
            CreateOrderResponse response = new CreateOrderResponse();
            response.setErrno(-2)
            response.setErrmsg("订单不存在")
            return JsonOutput.toJson(response)
        }
    } else {
        CreateOrderResponse response = new CreateOrderResponse();
        response.setErrno(-1)
        response.setErrmsg("认证失败")
        return JsonOutput.toJson(response)
    }

}

public class CreateOrderRequest {
    String client_id //	string	yes	申请应用时分配的AppKey
    String access_token //	string	yes	授权后的access token
    String timestamp //	int	yes	当前时间戳
    String sign //	string	yes	签名 详细算法参见 签名验证 章节
    String order_id //	string	yes	请求id 获取请参见 获取请求id
    int rule //	int	yes	计价模型分类，201(专车)；301(快车)
    int type //	int	yes	叫车车型，0(实时)；1(预约)
    String passenger_phone //	string	no	乘客手机号，不填表示给自己叫车
    int city //	int	yes	出发地城市
    double flat //	float	yes	出发地纬度
    double flng //	float	yes	出发地经度
    String start_name //	string	yes	出发地名称(最多50个字)
    String start_address //	string	no	出发地详细地址(最多100个字)
    double tlat //	float	no	目的地纬度(rule为201,301时必须)
    double tlng //	float	no	目的地经度(rule为201,301时必须)
    String end_name //	string	no	目的地名称(rule为201,301时必须,最多50个字)
    String end_address //	string	no	目的地详细地址(rule为201,301时必须,最多100个字)
    double clat //	float	no	当前位置纬度
    double clng //	float	no	当前位置经度
    String departure_time //	datetime	no	出发时间，不传表示现在用车（例如：2015-06-16 12:00:09）
    String require_level //	string	yes	所需车型,车型代码（专车如：100、200等；快车如：600等）
    String app_time //	datetime	yes	客户端时间（例如：2015-06-16 12:00:09）
    String map_type //	enum	no	地图类型，暂只支持soso
    int combo_id //	int	no	套餐id
    //int sms_policy //	int	no	发送短信策略(0,为叫车人和乘车人都发送，1，乘车人发送叫车人不发，2乘车人不发叫车人发，3乘车人和叫车人都不发)
    String extra_info //	string	no	备注
    String callback_info //	string	no	透传的内容，在回调的时候会原样传递(最多100字符)
    String dynamic_md5 //	string	yes	价格md5,通过 新的预估价接口获得
}

public class CreateOrderResponse {
    int errno //": 0,
    String errmsg //": "SUCCESS",
    Data data
}

public class Data {
    Price price
    Combo combo
    OrderDetail order
}

public class Price {
    String estimate
}

public class Combo {
    int time   //": 120,
    String distance   //": "12.1",
    String fee    //": "120.50"
}

public class OrderDetail {
    String id //": "4880109188406595918",
    String city //": "1",
    int type //": 0,
    String call_phone //": "13269661202",
    String passenger_phone  //": "13269661202",
    int status //": 300,
    double flng //": 116.307479,
    double flat //": 40.045724,
    double tlng //": 116.800012,
    double tlat //": 39.689123,
    double clng //": 116.800012,
    double clat //": 39.689123,
    String start_name //": "得实大厦",
    String start_address  //": "上地东路9号西南角",
    String end_name //": "万达广场",
    String end_address  //": "北京市石景山区万达广场",
    String departure_time //": "2015-03-11 17:06:58",
    String order_time //": "2015-03-11 17:06:58",
    String require_level  //": "100",
    String extra_info //": "这是订单备注",
}